package com.zyylr.classroomreservationsystem.fragment;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.widget.PullRefreshLayout;
import com.diegodobelo.expandingview.ExpandingItem;
import com.diegodobelo.expandingview.ExpandingList;
import com.wakehao.bar.BottomNavigationBar;
import com.zyylr.classroomreservationsystem.R;
import com.zyylr.classroomreservationsystem.bean.Classroom;
import com.zyylr.classroomreservationsystem.bean.Msg;
import com.zyylr.classroomreservationsystem.bean.Reservation;
import com.zyylr.classroomreservationsystem.consts.GlobalConsts;
import com.zyylr.classroomreservationsystem.utils.MyTimeUtils;
import com.zyylr.classroomreservationsystem.web.IReservation;
import com.zyylr.classroomreservationsystem.web.RetrofitFactory;

import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * 待审核的预约申请
 */
public class NotAuditedReservationFragment extends Fragment {
    private static String TAG = "待审核的预约申请";
    private ExpandingList reservationExpandingList;
    private PullRefreshLayout pullRefreshLayout;
    //可获取到下面的小红点
    private BottomNavigationBar bar;
    //预约记录数量，暨下面显示的小红点的数量
    private int reservationCounts;

    /**
     * 从服务器获取的待审核预约申请
     */
    private List<Reservation> reservationList;

    private Retrofit retrofit;

    public NotAuditedReservationFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_application_not_examine, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        reservationExpandingList = getActivity().findViewById(R.id.expanding_list_not_audited_reservation);
        bar = getActivity().findViewById(R.id.bar_audit_admin);
        retrofit = RetrofitFactory.getRetrofit();

        pullRefreshLayout = getActivity().findViewById(R.id.swipeRefreshLayout_not_audited);
        pullRefreshLayout.setRefreshStyle(PullRefreshLayout.STYLE_WATER_DROP);
        pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                pullRefreshLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        reservationExpandingList.removeAllViews();
                        sendHttpRequest();
                    }
                }, 0);
            }
        });
        pullRefreshLayout.setRefreshing(true);
        sendHttpRequest();
    }

    /**
     * 使用框架向服务器发送请求，得到响应数据存放在reservationList中
     */
    private void sendHttpRequest() {
        IReservation request = retrofit.create(IReservation.class);
        Call<Msg<List<Reservation>>> msgCall = request.getNotAuditedReservationsCall();
        msgCall.enqueue(new Callback<Msg<List<Reservation>>>() {
            @Override
            public void onResponse(Call<Msg<List<Reservation>>> call, Response<Msg<List<Reservation>>> response) {
                Msg msg = response.body();
                Log.d(TAG, "msg= " + msg);
                try {
                    assert msg != null;
                    if (msg.getCode() == 200) {
                        Toast.makeText(getContext(), msg.getMsg(), Toast.LENGTH_SHORT).show();
                        pullRefreshLayout.setRefreshing(false);
                        return;
                    }
                    reservationList = (List<Reservation>) msg.getExtend().get("reservations");
                    reservationCounts = reservationList.size();
                    Log.d(TAG, "reservationList= " + reservationList);
                    createItems();
                } catch (Exception e) {
                    Toast.makeText(getContext(), "数据解析错误！", Toast.LENGTH_SHORT).show();
                    Log.e(TAG, e.getMessage());
                } finally {
                    pullRefreshLayout.setRefreshing(false);
                }
            }

            @Override
            public void onFailure(Call<Msg<List<Reservation>>> call, Throwable t) {
                Toast.makeText(getContext(), "服务请求错误！", Toast.LENGTH_SHORT).show();
                pullRefreshLayout.setRefreshing(false);
            }
        });
    }

    /**
     * 使用服务器返回的reservationList数据创建listview的item
     */
    private void createItems() {
        if (reservationList == null) {
            Log.d(TAG, "createItems: reservationList为空！");
            return;
        }
        bar.showNum(0, reservationCounts);
        for (Reservation reservation : reservationList) {
            ExpandingItem item = reservationExpandingList.createNewItem(R.layout.expanding_layout_not_audited_reservation);
            Classroom classroom = reservation.getClassroom();
            String classroomName = classroom.getName();
            String buildingName = classroom.getBuilding().getName();

            int buildingColorRes, buildingIconRes;
            switch (buildingName) {
                case "博约楼":
                    buildingColorRes = R.color.blue;
                    buildingIconRes = R.drawable.building_boyuelou;
                    break;
                case "逸夫楼":
                    buildingColorRes = R.color.green;
                    buildingIconRes = R.drawable.building_yifulou;
                    break;
                case "躬行楼":
                    buildingColorRes = R.color.purple;
                    buildingIconRes = R.drawable.building_gongxinglou;
                    break;
                case "履知楼":
                    buildingColorRes = R.color.yellow;
                    buildingIconRes = R.drawable.building_lvzhilou;
                    break;
                default:
                    buildingColorRes = R.color.blue;
                    buildingIconRes = R.drawable.building_boyuelou;
                    break;
            }
            //设置颜色和图标
            item.setIndicatorColorRes(buildingColorRes);
            item.setIndicatorIconRes(buildingIconRes);
            //设置教学楼和教室名
            TextView tvClassroom = item.findViewById(R.id.tv_not_audited_classroom);
            tvClassroom.setText(String.format("%s%s", buildingName, classroomName));
            //设置预约时间段
            Date startTime = reservation.getStart_time();
            Date endTime = reservation.getEnd_time();
            TextView tvTime = item.findViewById(R.id.tv_not_examine_information_time);
            tvTime.setText(String.format("%s — %s",
                    MyTimeUtils.formatDateWithoutYearAndSecond(startTime),
                    MyTimeUtils.formatDateWithoutYearAndSecond(endTime)));
            //设置用户名
            String username = reservation.getUser().getName();
            TextView tvUsername = item.findViewById(R.id.tv_not_examine_information_user);
            tvUsername.setText(username);
            //  创建子item，通过or不通过
            item.createSubItems(2);
            View subItemView1 = item.getSubItemView(0);
            TextView tv1 = subItemView1.findViewById(R.id.tv_pass_or_not_pass);
            tv1.setText("通过");
            //  添加监听器
            addOnClickedListener(tv1, item, true, reservation);
            View subItemView2 = item.getSubItemView(1);
            TextView tv2 = subItemView2.findViewById(R.id.tv_pass_or_not_pass);
            tv2.setText("不通过");
            addOnClickedListener(tv2, item, false, reservation);
        }
    }

    /**
     * 给子item添加监听器，召唤对话框
     *
     * @param view        被点击的view
     * @param parentItem  触发的对话框的那个item的父item，方便对其进行删除
     * @param isPass      通过->true 不通过->false
     * @param reservation 要处理的预约记录
     */
    private void addOnClickedListener(View view, ExpandingItem parentItem, boolean isPass, Reservation reservation) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showConfirmDialog(parentItem, isPass, reservation);
            }
        });
    }

    /**
     * 显示确认对话框
     *
     * @param item        触发的对话框的那个item的父item，方便对其进行删除
     * @param isPass      通过->true 不通过->false
     * @param reservation 要处理的预约记录
     */
    private void showConfirmDialog(ExpandingItem item, boolean isPass, Reservation reservation) {
        String title = "";
        if (isPass) {
            title = "通过审核？";
        } else {
            title = "不通过审核？";
        }
        AlertDialog.Builder builder;
        builder = new AlertDialog.Builder(getContext())
                .setMessage("确认" + title)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Log.d(TAG, "预约记录" + reservation.getId() + " isPass?: " + isPass + " 准备发起http请求");
                        if (isPass) {
                            reservation.setStatus(GlobalConsts.STATUS_PASSED);
                        } else {
                            reservation.setStatus(GlobalConsts.STATUS_FAILED);
                        }
                        sendHttp2UpdateReservation(reservation, item);
                        dialogInterface.dismiss();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //什么也不做，直接让对话框消失
                        dialogInterface.dismiss();
                    }
                });
        builder.create().show();
    }

    /**
     * 发送请求更新记录，更新的数据有：审核状态
     * 1.提交数据到数据库
     * 2.如果更新数据成功，则删除该item，更新小红点；否则提示删除失败，删除对话框
     *
     * @param reservation 预约
     * @param item        触发的对话框的那个item的父item，方便对其进行删除
     */
    private void sendHttp2UpdateReservation(Reservation reservation, ExpandingItem item) {
        IReservation request = retrofit.create(IReservation.class);
        Call<Msg> msgCall = request.getReservationCall(reservation);
        msgCall.enqueue(new Callback<Msg>() {
            @Override
            public void onResponse(Call<Msg> call, Response<Msg> response) {
                Msg msg = response.body();
                Log.d(TAG, "发起预约申请服务器返回的信息：" + msg);
                if (msg.getCode() == 200) {
                    Toast.makeText(getContext(), "审核失败！", Toast.LENGTH_SHORT).show();
                    //设回未审核状态
                    reservation.setStatus(GlobalConsts.STATUS_NOT_AUDITED);
                } else {
                    Toast.makeText(getContext(), "审核成功！", Toast.LENGTH_SHORT).show();
                    reservationExpandingList.removeItem(item);
                    //小红点数字减少
                    reservationCounts--;
                    bar.showNum(0, reservationCounts);
                }
            }

            @Override
            public void onFailure(Call<Msg> call, Throwable t) {
                Toast.makeText(getContext(), "服务请求错误！", Toast.LENGTH_SHORT).show();
                //设回未审核状态
                reservation.setStatus(GlobalConsts.STATUS_NOT_AUDITED);
            }
        });
    }

}
